$.extend({
    /**
     * 获取当前页面所有的get参数
     * @returns {{}}
     */
    getPageParam() {
        return $.getQueryParam(window.location.search);
    },
    /**
     * 获取传入的查询串
     * @param query
     * @returns {{}}
     */
    getQueryParam(query = "") {
        const reg = /([^?=&]+)=([^?=&]+)/g
        const param = {};
        query.replace(reg, (...arg) => {
            param[arg[1]] = decodeURIComponent(arg[2])
        })
        return param;
    },

    /**
     * url参数的包装方法
     * @param url url
     * @param param 附加的参数
     * @param transfer 页面需要透传的参数
     * @returns {string}
     */
    sUrl(url, param = {}, transfer = ["token"]) {

        const pageParam = $.getPageParam();
        const transferParam = {};
        transfer.forEach(key => {
            transferParam[key] = pageParam[key];
        });

        param = {...transferParam, ...param}

        if (url.indexOf('?') >= 0) {
            const [newUrl, query] = url.split('?');
            url = newUrl;
            param = {...$.getQueryParam(query), ...param};
        }

        return url + "?" + $.param(param);
    },
    /**
     * 获取表单内容
     * @param $form jquery的form对象
     * @returns {{}}
     */
    getFormData($form) {
        if (!$form || $form.length === 0) {
            return {};
        }
        const data = {};
        $form.serializeArray().forEach(item => {
            const name = item.name;
            data[name] = $.trim(item.value);
        })
        return data;
    },
    /**
     * 简单包装ajax(代入一些默认值和loading)
     * @param param
     * @returns {*}
     */
    sAjax(param) {
        param = {
            timeout: 80000,
            type: 'post',
            async: true,
            showLoading: true,
            beforeSend: Function(),
            complete: Function(),
            ...param
        }

        if (param.showLoading) {
            const beforeSend = param.beforeSend;
            const complete = param.complete;

            let $loadingWidget;
            param.beforeSend = () => {
                $loadingWidget = $.loading();
                beforeSend();
            }

            param.complete = () => {
                complete();
                $loadingWidget.remove();
            }
        }

        return $.ajax(param);
    },

    /**
     * 带有回调的ajax调用
     * @param param
     * @param callback
     * @returns {*}
     */
    sApi(param, callback = Function()) {
        param = {
            ...param,
            success: res => {
                if (typeof res === "string") {
                    try {
                        res = JSON.parse(res);
                    } catch (e) {
                        res = {
                            Code: -14444,
                            Message: "返回格式不是JSON"
                        }
                    }
                }

                //登录异常
                if (res.Code === -11000) {
                    return location.href = "/WxMp/mpAuth?" + $.param({back: window.location.href});
                }

                callback(res);
            },
            error() {
                callback({
                    Code: -14444,
                    Message: "网络响应超时"
                });
            }
        }

        const {token} = $.getPageParam();
        if (token) {
            param.headers = {
                Authorization: `Bearer ${token}`
            }
        }


        return $.sAjax(param);
    },

    /**
     * 自定义的loading
     * @param msg
     * @returns {*|jQuery|HTMLElement}
     */
    loading(msg = "加载中...") {
        const $widget = $(`<div class="mask" ></div>`);
        $('body').append($widget);

        const $div = $(`<div class="c-load-box">
            <span class="loadgif"></span>
            <p> ${msg}</p>
        </div>`);

        $widget.append($div);
        $div.css("left", ($widget.width() - $div.width()) / 2 - 20);

        return $widget;
    },

    /**
     * 自定义的toast
     * @param msg
     * @param time
     * @param callback
     */
    toast(msg = "", time = 3000, callback = Function()) {
        const $widget = $(`<div class="mask" ></div>`);
        $('body').append($widget);

        if (msg instanceof jQuery) {
            $widget.append(msg);
        } else {
            const $p = $(`<p class="c-alert-box">${msg}</p>`)
            $widget.append($p);

            $p.css("left", ($widget.width() - $p.width()) / 2);

        }

        $widget.on("click", () => {
            $widget.remove();
            callback();
        });

        setTimeout(() => {
            $widget.remove();
            callback();
        }, time);
    },

    /**
     * 自定义的dialog
     * @param content
     * @param param
     * @returns {*|jQuery|HTMLElement}
     */
    dialog(content, param = {}) {
        param = {
            title: "提示",
            okTitle: "确定",
            cancelTitle: "取消",
            init: Function(),
            ok: Function(),
            cancel: Function(),
            ...param
        }

        const $widget = $(`
            <div class="mask">
                <div class="mask-main">
                    <p class="m-tit" data-type="title">${param.title}</p>
                    <div class="m-des" data-type="content"></div>
                    <div class="m-bot" data-type="btnGroup"></div>
                </div>
            </div>
        `);

        const $contentWrap = $widget.find('[data-type="content"]');
        const $btnGroupWrap = $widget.find('[data-type="btnGroup"]');

        //弹窗内容插入，支持jquery对象
        $contentWrap.append(content);

        const {ok, cancel} = param;
        if (ok || cancel) {
            if (cancel) {
                const $cancelBtn = $(`<a class="btn-cancel" href="javascript:;">${param.cancelTitle}</a>`);
                $btnGroupWrap.append($cancelBtn);
                $cancelBtn.on("click", () => {
                    if (cancel() !== false) {
                        $widget.remove();
                    }
                });
            }

            if (ok) {
                const $okBtn = $(`<a class="btn-submit" href="javascript:;">${param.okTitle}</a>`);
                $btnGroupWrap.append($okBtn);
                $okBtn.on("click", () => {
                    if (ok() !== false) {
                        $widget.remove();
                    }
                })
            }
        } else {
            //无操作按钮，移除按钮组
            $btnGroupWrap.remove();
        }

        //运行初始化
        param.init($contentWrap);

        $('body').append($widget);
        return $widget;
    },

    /**
     * 省份城市选择控件
     * @param param
     * @returns {*|jQuery|HTMLElement}
     */
    getCitySelect(param) {
        param = {
            level: 2,
            placeholder: null,
            callback: Function(),
            ...param
        };

        if (!param.placeholder) {
            const placeholderDict = {1: "请选择省份", 2: "请选择省/市"}
            param.placeholder = placeholderDict[param.level];
        }

        const $widget = $(`
            <div class="iarea-hold">
                <div class="iarea-choose">
                    <div class="iarea-top">
                        <a data-btn="cancel" href="javascript:;" class="iarea-cancel">取消</a>
                        ${param.placeholder}
                    </div>
                    <div class="iarea-sel">
                        <a data-btn="curr" href="javascript:;" class="curr">请选择</a>
                    </div>
                    <div class="iarea-box">
                        <div class="preiarea">
                            <ul data-wrap="1" ></ul>
                        </div>
                    </div>
                </div>
                <div class="iarea-choose-mb"></div>
            </div>
        `);

        let currAreaInfo = {
            provinceId: null,
            provinceName: null,
            cityId: null,
            cityName: null
        };

        const $wrap = $widget.find('[data-wrap="1"]');
        const $currBtn = $widget.find('[data-btn="curr"]');
        initProvinceLi();

        $widget.find('[data-btn="cancel"]').on("click", () => {
            $widget.remove();
        });

        $widget.find('.iarea-choose-mb').on("click", () => {
            $widget.remove();
        })

        $currBtn.on("click", () => {
            $currBtn.addClass("curr").siblings().removeClass("curr");
            if (currAreaInfo.provinceId) {
                initCityLi(currAreaInfo.provinceId)
            } else {
                initProvinceLi();
            }
        });

        function initCityLi(provinceId) {
            $wrap.html("");
            getCityList(provinceId, cityList => {
                cityList.forEach(({cityId, cityName}) => {
                    const $li = $(`<li data-val="${cityName}" data-code="${cityId}">${cityName}</li>`)
                    if (cityId === currAreaInfo.cityId) {
                        $li.addClass("curr")
                    }
                    $wrap.append($li);

                    $li.on("click", () => {
                        $li.addClass("curr").siblings().removeClass("curr");
                        currAreaInfo.cityId = cityId;
                        currAreaInfo.cityName = cityName;

                        param.callback(currAreaInfo);
                        return $widget.remove();
                    })

                });
            });

            function getCityList(provinceId, callback = Function()) {
                if ($.cityList && $.cityList[provinceId]) {
                    return callback($.cityList[provinceId]);
                }
                queryCityListByProvinceId({provinceId}, ({Result: cityList}) => {
                    if (!$.cityList) {
                        $.cityList = {};
                    }
                    $.cityList[provinceId] = cityList;
                    return callback($.cityList[provinceId]);
                })
            }
        }


        function initProvinceLi() {
            $wrap.html("");
            getProvinceList(provinceList => {
                provinceList.forEach(({provinceId, provinceName}) => {
                    const $li = $(`<li data-val="${provinceName}" data-code="${provinceId}">${provinceName}</li>`)
                    if (provinceId === currAreaInfo.provinceId) {
                        $li.addClass("curr")
                    }
                    $wrap.append($li);

                    $li.on("click", () => {
                        currAreaInfo = {
                            provinceId,
                            provinceName,
                            cityId: null,
                            cityName: null
                        };
                        $li.addClass("curr").siblings().removeClass("curr");

                        if (param.level === 1) {
                            param.callback(currAreaInfo);
                            return $widget.remove();
                        }

                        initCityLi(provinceId);

                        $currBtn.siblings().remove();
                        const $provinceTab = $(`<a href="javascript:;" class="">${provinceName}</a>`);
                        $currBtn.before($provinceTab);
                        $provinceTab.on("click", () => {
                            $provinceTab.addClass("curr").siblings().removeClass("curr");
                            initProvinceLi();
                        })

                    })

                });
            });

            function getProvinceList(callback = Function()) {
                if ($.provinceList && $.provinceList.length) {
                    return callback($.provinceList);
                }
                queryProvinceList(({Result: provinceList}) => {
                    $.provinceList = provinceList || [];
                    return callback($.provinceList);
                })
            }
        }


        function queryProvinceList(callback = Function()) {
            $.sApi({
                url: "/Area/queryProvinceList",
            }, callback)
        }

        function queryCityListByProvinceId(data, callback = Function()) {
            $.sApi({
                data,
                url: "/Area/queryCityListByProvinceId",
            }, callback)
        }

        return $widget;
    },

    /**
     * 图片上传控件
     * @param param
     * @returns {{val(*): void}}
     */
    uploadImageWidget(param) {
        const {$widget = $('<div></div>'), callback = Function()} = param;
        const imgList = [];

        const $addBtn = $(`<li class="file-add"></li>`);
        $widget.append($addBtn);

        $addBtn.on("click", () => {
            wxUploadFile({
                uploadApiUrl: "/File/uploadWxImage",
                callback({Code, Message, Result}) {
                    if (Code !== 10000) {
                        return $.toast(Message);
                    }
                    Result.forEach(url => {
                        $addBtn.before(getImgCard(url));
                    });
                }
            });
        });

        return {
            type: "uploadImageWidget",
            $widget,
            val(urls = "") {
                if (!urls) {
                    return;
                }
                urls.split(",").forEach(url => {
                    $addBtn.before(getImgCard(url));
                });
            }
        }

        function getImgCard(url) {
            imgList.push(url);

            const $card = $(`
                <li>
                    <div class="file-img">
                        <img src="${url}" class="c-photoswipe" alt="">
                        <a href="javascript:;" data-btn="del" class="file-delete"><i class="iconfont icon-shanchu"></i></a>
                    </div>
                </li>
            `);

            $card.find('[data-btn="del"]').on("click", () => {
                imgList.splice(imgList.findIndex(item => item === url), 1);
                callback(imgList);
                $card.remove();
            })

            callback(imgList);

            return $card;
        }

    }
})

/**
 * 页面js跳转
 */
$(document).on("click", "[data-jump]", function () {
    const href = $(this).attr('data-jump');
    if (!href) {
        location.reload();
    } else {
        location.href = $.sUrl(href);
    }
});


